package org.sunyaxing.transflow.transflowapp.plugins.filters;

import com.alibaba.fastjson2.JSONObject;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sunyaxing.transflow.api.TransData;
import org.sunyaxing.transflow.api.common.Handle;
import org.sunyaxing.transflow.api.common.ano.Extension;
import org.sunyaxing.transflow.api.common.ano.HandleItem;
import org.sunyaxing.transflow.api.common.ano.ScopeContentCheck;
import org.sunyaxing.transflow.api.extensions.base.ExtensionContext;
import org.sunyaxing.transflow.api.extensions.base.typesimpl.TransFlowMiddleJsonGatewayHandler;
import org.sunyaxing.transflow.transflowapp.controllers.JobLogsWs;

import java.util.List;
import java.util.function.Function;

@Extension("plugin-json-filter")
@ScopeContentCheck(
        handle = @HandleItem(field = "config", label = "脚本", required = true, type = "code", defaultValue = "")
)
public class JsonFilterExt extends TransFlowMiddleJsonGatewayHandler {
    private static final Logger log = LoggerFactory.getLogger(JsonFilterExt.class);

    public JsonFilterExt(ExtensionContext extensionContext) {
        super(extensionContext);
    }

    @Override
    protected void afterInitHandler(JSONObject config, List<Handle> handles) {

    }

    @Override
    public Function<TransData<JSONObject>, Boolean> parseHandleToConsumer(String handleId, String handleValue) {
        Expression expression = AviatorEvaluator.compile(handleValue);
        log.info("编译完成 \n {}", expression);
        return transData -> {
            JSONObject env = new JSONObject();
            env.put("data", transData.getData());
            Object result = expression.execute(env);
            JobLogsWs.sendMessage(jobId, "【{}】filter 处理结果 {}", extensionContext.getNodeName(), result);
            JobLogsWs.sendMessage(jobId, "【{}】发送数据 {}", extensionContext.getNodeName(), transData.getData().toJSONString());
            boolean resultIsBool = result instanceof Boolean;
            return !resultIsBool || Boolean.TRUE.equals(result);
        };
    }

    @Override
    public void destroy() {
        log.info("jsonfilter destroy");
    }
}
